package com.ztesoft.zsmart.zcm.monitor.utils;

import com.ztesoft.zsmart.core.log.ZSmartLogger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public final class UtcTimeUtil {
    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(UtcTimeUtil.class);

    public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS Z";

    public static final String UTC_FORMAT_NO_SSS = "yyyy-MM-dd'T'HH:mm:ss Z";

    private static final String REGEX_UTC = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d+Z$";

    private static final String REGEX_UTC_NO_SSS = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$";

    private static final Pattern pattern1 = Pattern.compile(REGEX_UTC);

    private static final Pattern pattern2 = Pattern.compile(REGEX_UTC_NO_SSS);

    private UtcTimeUtil() {

    }

    public static Date utcTimeToLocalDate(String utcTime) {
        SimpleDateFormat sdf = null;
        if (pattern1.matcher(utcTime).matches()) {
            sdf = new SimpleDateFormat(UTC_FORMAT);
        }
        else if (pattern2.matcher(utcTime).matches()) {
            sdf = new SimpleDateFormat(UTC_FORMAT_NO_SSS);
        }
        else {
            sdf = new SimpleDateFormat(DEFAULT_FORMAT);
        }
        String date = utcTime.replace("Z", " UTC");
        try {
            LOGGER.info(date);
            return sdf.parse(date);
        }
        catch (Exception e) {
            LOGGER.error(e);
        }
        return new Date();
    }

    /**
     * 将本地时间字符串转换为UTC时间字符串
     * yyyy-MM-dd HH:mm:ss 转为 yyyy-MM-dd'T'HH:mm:ss.SSS Z
     *
     * @param dateTime String 格式为yyyy-MM-dd HH:mm:ss
     * @return String
     */
    public static String turnToUTC(String dateTime) {
        return DateTime.parse(dateTime, DateTimeFormat.forPattern(DEFAULT_FORMAT)).withZone(DateTimeZone.UTC)
                .toString();
    }

    /**
     * 返回日时分秒
     *
     * @param second
     * @return
     */
    public static String secondToTime(long second) {
        //转换天数
        long days = second / 86400;
        //剩余秒数
        second = second % 86400;
        //转换小时数
        long hours = second / 3600;
        //剩余秒数
        second = second % 3600;
        //转换分钟
        long minutes = second / 60;
        //剩余秒数
        second = second % 60;
        if (0 < days) {
            return days + "天" + hours + "小时" + minutes + "分" + second + "秒";
        }
        else {
            return hours + "小时" + minutes + "分" + second + "秒";
        }
    }
}
